package com.youedata.sys.core.util;

import cn.stylefeng.roses.core.util.ToolUtil;
import com.youedata.base.auth.jwt.JwtTokenUtil;
import com.youedata.base.consts.ConstantsContext;
import com.youedata.base.exception.BusinessException;
import com.youedata.base.utils.HttpKit;
import com.youedata.modular.model.dto.UserInfoDTO;
import com.youedata.modular.model.vo.User;
import com.youedata.sys.core.exception.enums.BizMyExceptionEnum;
import com.youedata.sys.modular.system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description 用户信息KIT
 * @Author zhangzb
 * @Date 2020/1/4
 */
@Slf4j
@Component
public class UserKit {

    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    public static String USERTOKEN = ConstantsContext.getTokenHeaderName();

    /**
     * 解析用户信息
     *
     * @param params
     * @return
     */
    public UserInfoDTO getUserInfoDTO(String params) {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        String plain;
        try {
//            plain = RSAUtils.decrypt(params,privateKey);
            plain = AESUtil.aesDecrypt(params, aesKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(BizMyExceptionEnum.USER_DECRYPT_FAILD);
        }
        try {
            String[] paramArr = plain.split("&");
            for (String p : paramArr) {
                String[] strings = p.split("=");
                String key = strings[0];
                String value = strings[1];

                if (StringUtils.equals("userid", key)) {
                    userInfoDTO.setUserid(value);
                } else if (StringUtils.equals("useridgroup", key)) {
                    userInfoDTO.setUseridgroup(value);
                } else if (StringUtils.equals("username", key)) {
                    userInfoDTO.setUsername(value);
                } else if (StringUtils.equals("timestamp", key)) {
                    userInfoDTO.setTimestamp(Long.valueOf(value));
                }
            }

            if (StringUtils.isBlank(userInfoDTO.getUserid())
                    || StringUtils.isBlank(userInfoDTO.getUseridgroup())
                    || StringUtils.isBlank(userInfoDTO.getUsername())
                    || userInfoDTO.getTimestamp() == null) {
                throw new BusinessException(BizMyExceptionEnum.USER_INVALID_PARAM);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(BizMyExceptionEnum.USER_INVALID_PARAM);
        }
        return userInfoDTO;
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    public User getUser() {
        String token = getToken();
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(BizMyExceptionEnum.TOKEN_EXPIRED_NOT_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userMapper.selectById(jwtTokenUtil.getUserIdFromToken(token)), user);
        return user;
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    public com.youedata.sys.modular.system.entity.User getSysUser() {
        String token = getToken();
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(BizMyExceptionEnum.TOKEN_EXPIRED_NOT_EXIST);
        }
        return userMapper.selectById(jwtTokenUtil.getUserIdFromToken(token));
    }

    /**
     * 获取当前用户的ID
     *
     * @return
     */
    public Long getUserId() {
        String token = getToken();
        if (ToolUtil.isNotEmpty(token)) {
            return jwtTokenUtil.getUserIdFromToken(token);
        }
        return null;
    }

    /**
     * 获取当前用户的token
     */
    public String getToken() {
        HttpServletRequest request = HttpKit.getNativeRequest();
        if (ToolUtil.isEmpty(request)) {
            return null;
        }

        final String requestHeader = HttpKit.getNativeRequest().getHeader(USERTOKEN);
        log.info("requestHeader-{}", requestHeader);

        String authToken = null;
        // 1.从cookie中获取token
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (ConstantsContext.getTokenHeaderName().equals(cookie.getName())) {
                    authToken = cookie.getValue();
                }
            }
        }

        // 2.如果cookie中没有token，则从header中获取token
        if (ToolUtil.isEmpty(authToken)) {
            if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
                authToken = requestHeader.substring(7);
            }
        }

        log.info("authToken-{}", authToken);
        return authToken;
    }

    /**
     * 获取部门以及子部门IDs
     */
    public List<Long> getDeptIds() {
        String token = getToken();
        return userMapper.selectDeptIdsByDeptId(userMapper.selectById(jwtTokenUtil.getUserIdFromToken(token)).getDeptId());
    }

}
